define(()=>{
class addcart {
    constructor() {

        this.init()

    }
    init(){
       this.ajax()
       this. count()

    }
    // 获取地址传过来的数据
getid(name) {
        var str = location.search.slice(1)
        var arr = str.split("&")
    
        var obj = {}
        arr.forEach((item) => {
            let newarr = item.split("=")
            obj[newarr[0]] = newarr[1]
    
    
        })
    
        return obj[name]
    


}


// 发送请求
ajax(){
$.ajax({
    url: "../data/goods.json",
    dataType: "json",
    type: "get"

}).then((res) => {

    let goods = res.find((item) => {
        return item.goods_id ==this.getid("id")
    })

   this.rander(goods)

})
}
// 渲染页面
 rander(goods) {
    $(".navv-l")[0].innerHTML = goods.category
    $("h1")[0].innerHTML = goods.title
    $(".smallimge img")[0].src = goods.img_small_logo
    $(".magnifier img")[0].src = goods.img_small_logo
    $(".left ul  li img").eq(0).attr("src", goods.img_small_logo)
    $(".page").html(goods.goods_introduce)
    $(".price").html(goods.price)
    $(".add").attr("id", goods.goods_id)
    this.btn(goods)


}

// 绑定购物车添加事件
 btn(goods) {

    $(".add").click( ()=> {
        let list = JSON.parse(localStorage.getItem("cart")) || []
        // 判断有没有数据
        if (!list.length) {
            list.push(goods)
            goods.cart_number = 1

        }
        // 有数据
        else {
            let res = list.some((item) => {
                return item.goods_id == goods.goods_id
            })
            if (res) {

                let index = list.findIndex((item) => {
                    return item.goods_id == goods.goods_id
                })

                list[index].cart_number++

            } else {

                list.push(goods)
                goods.cart_number = 1


            }


        }

        localStorage.setItem("cart", JSON.stringify(list))
        this.count()
        if (getCookie("username") == undefined) {
            if (confirm("登录之后才能去购物车")) {

                if (confirm("要去登录?")) {
                    location.href = "./logon.html"


                }

            }

        } else {

            if (confirm("加入成功,去购物车?")) {
                location.href = "./Shopping.html"


            } else {
                return false;
            }

        }
    })

}

// 改变固定框里面的数 
 count() {
    let list = JSON.parse(localStorage.getItem("cart")) || []
    let num = 0
    list.forEach(item => {
        num += item.cart_number

    })

    $(".goshopp").html(num)

  

}
}
return   new addcart()
})